<?php

namespace app\service;

use app\model\ApijsonLog;
use support\Log;

/**
 * APIJSON调试日志服务
 * 专门用于记录APIJSON的解析和执行过程，便于调试
 */
class ApijsonDebugService
{
    /**
     * 记录APIJSON调试信息
     *
     * @param array $requestData 请求数据
     * @param array $responseData 响应数据
     * @param array $executionInfo 执行信息
     * @return void
     */
    public static function logDebugInfo(array $requestData, array $responseData, array $executionInfo): void
    {
        try {
            $logData = array_merge($requestData, $responseData, $executionInfo);
            ApijsonLog::createLog($logData);
            
            // 同时记录到日志文件，便于调试
            Log::info('APIJSON调试信息', [
                'request_id' => $logData['request_id'],
                'endpoint' => $logData['endpoint'],
                'execution_time' => $logData['execution_time'],
                'record_count' => $logData['record_count'],
                'is_success' => $logData['is_success'],
            ]);
        } catch (\Exception $e) {
            Log::error('APIJSON调试日志记录失败: ' . $e->getMessage());
        }
    }

    /**
     * 创建请求数据记录
     *
     * @param string $requestId 请求ID
     * @param array $originalRequest 原始请求JSON
     * @param array $parsedRequest 解析后的请求JSON
     * @param array $headers 请求头
     * @param string $endpoint 端点
     * @param array $userInfo 用户信息
     * @return array
     */
    public static function createRequestData(
        string $requestId,
        array $originalRequest,
        array $parsedRequest,
        array $headers,
        string $endpoint,
        array $userInfo = []
    ): array {
        return [
            'request_id' => $requestId,
            'caller_type' => 'frontend',
            'endpoint' => $endpoint,
            'request_json' => [
                'original' => $originalRequest,
                'parsed' => $parsedRequest,
                'parsed_at' => date('Y-m-d H:i:s'),
            ],
            'request_headers' => self::filterHeaders($headers),
            'space_id' => $userInfo['space_id'] ?? null,
            'user_id' => $userInfo['user_id'] ?? null,
            'user_type' => $userInfo['user_type'] ?? 'admin',
            'ip_address' => $userInfo['ip_address'] ?? null,
            'user_agent' => $userInfo['user_agent'] ?? null,
            'api_version' => $userInfo['api_version'] ?? 'v1',
        ];
    }

    /**
     * 创建响应数据记录
     *
     * @param array $responseJson 响应JSON
     * @param array $sqlQueries SQL查询数组
     * @param int $recordCount 记录数量
     * @param bool $isSuccess 是否成功
     * @param string|null $errorMessage 错误信息
     * @param string|null $errorCode 错误代码
     * @return array
     */
    public static function createResponseData(
        array $responseJson,
        array $sqlQueries = [],
        int $recordCount = 0,
        bool $isSuccess = true,
        ?string $errorMessage = null,
        ?string $errorCode = null
    ): array {
        return [
            'response_json' => $responseJson,
            'sql_queries' => implode('; ', $sqlQueries),
            'record_count' => $recordCount,
            'is_success' => $isSuccess ? 1 : 0,
            'error_message' => $errorMessage,
            'error_code' => $errorCode,
        ];
    }

    /**
     * 创建执行信息记录
     *
     * @param int $executionTime 执行时间(毫秒)
     * @param int $memoryUsage 内存使用量(字节)
     * @param array $debugInfo 额外调试信息
     * @return array
     */
    public static function createExecutionInfo(int $executionTime, int $memoryUsage, array $debugInfo = []): array
    {
        return [
            'execution_time' => $executionTime,
            'memory_usage' => $memoryUsage,
            'debug_info' => $debugInfo,
        ];
    }

    /**
     * 生成请求ID
     *
     * @return string
     */
    public static function generateRequestId(): string
    {
        return 'debug_' . uniqid() . '_' . mt_rand(1000, 9999);
    }

    /**
     * 获取用户信息
     *
     * @param array $headers 请求头
     * @param string $ipAddress IP地址
     * @param string $userAgent 用户代理
     * @return array
     */
    public static function getUserInfo(array $headers, string $ipAddress, string $userAgent): array
    {
        $userInfo = [
            'ip_address' => $ipAddress,
            'user_agent' => $userAgent,
            'space_id' => null,
            'user_id' => null,
            'user_type' => 'guest',
        ];

        // 从Authorization头中提取JWT token信息
        $authHeader = $headers['Authorization'] ?? $headers['authorization'] ?? null;
        if ($authHeader && strpos($authHeader, 'Bearer ') === 0) {
            $token = substr($authHeader, 7);
            $payload = self::decodeJwtToken($token);
            
            if ($payload) {
                $userInfo['space_id'] = $payload['extend']['space_id'] ?? null;
                $userInfo['user_id'] = (string)($payload['extend']['id'] ?? $payload['extend']['user_id'] ?? null);
                $userInfo['user_type'] = 'admin'; // 默认admin类型
            }
        }

        return $userInfo;
    }

    /**
     * 解码JWT token
     *
     * @param string $token
     * @return array|null
     */
    private static function decodeJwtToken(string $token): ?array
    {
        try {
            $parts = explode('.', $token);
            if (count($parts) !== 3) {
                return null;
            }
            
            $payload = base64_decode(str_replace(['-', '_'], ['+', '/'], $parts[1]));
            return json_decode($payload, true) ?: null;
        } catch (\Exception $e) {
            return null;
        }
    }

    /**
     * 计算记录数量
     *
     * @param array $responseJson
     * @return int
     */
    public static function calculateRecordCount(array $responseJson): int
    {
        // 尝试从APIJSON响应中提取记录数量
        if (isset($responseJson['[]'])) {
            return count($responseJson['[]']);
        }

        if (isset($responseJson['data'])) {
            if (is_array($responseJson['data'])) {
                return count($responseJson['data']);
            }
            return 1;
        }

        // 如果响应中有数字类型的字段，可能是记录数
        foreach ($responseJson as $value) {
            if (is_numeric($value)) {
                return (int)$value;
            }
        }

        return 1;
    }

    /**
     * 提取SQL查询
     *
     * @param array $responseJson
     * @return array
     */
    public static function extractSqlQueries(array $responseJson): array
    {
        $sqlQueries = [];
        
        if (isset($responseJson['sql'])) {
            if (is_array($responseJson['sql'])) {
                $sqlQueries = $responseJson['sql'];
            } else {
                $sqlQueries = [$responseJson['sql']];
            }
        }

        return $sqlQueries;
    }

    /**
     * 过滤敏感请求头
     *
     * @param array $headers
     * @return array
     */
    public static function filterHeaders(array $headers): array
    {
        $sensitiveHeaders = ['authorization', 'cookie', 'x-api-key', 'x-auth-token'];
        
        $filtered = [];
        foreach ($headers as $key => $value) {
            $lowerKey = strtolower($key);
            if (in_array($lowerKey, $sensitiveHeaders)) {
                $filtered[$key] = '[REDACTED]';
            } else {
                $filtered[$key] = is_array($value) ? implode(', ', $value) : $value;
            }
        }
        
        return $filtered;
    }

    /**
     * 记录解析错误
     *
     * @param string $requestId
     * @param array $originalRequest
     * @param string $errorMessage
     * @param array $headers
     * @param string $endpoint
     * @param array $userInfo
     * @return void
     */
    public static function logParseError(
        string $requestId,
        array $originalRequest,
        string $errorMessage,
        array $headers,
        string $endpoint,
        array $userInfo
    ): void {
        $requestData = [
            'request_id' => $requestId,
            'caller_type' => 'frontend',
            'endpoint' => $endpoint,
            'request_json' => [
                'original' => $originalRequest,
                'parse_error' => true,
                'error_message' => $errorMessage,
                'parsed_at' => date('Y-m-d H:i:s'),
            ],
            'request_headers' => self::filterHeaders($headers),
            'space_id' => $userInfo['space_id'] ?? null,
            'user_id' => $userInfo['user_id'] ?? null,
            'user_type' => $userInfo['user_type'] ?? 'admin',
            'ip_address' => $userInfo['ip_address'] ?? null,
            'user_agent' => $userInfo['user_agent'] ?? null,
            'api_version' => $userInfo['api_version'] ?? 'v1',
        ];

        $responseData = [
            'response_json' => null,
            'sql_queries' => null,
            'record_count' => 0,
            'is_success' => 0,
            'error_message' => $errorMessage,
            'error_code' => 'PARSE_ERROR',
        ];

        $executionInfo = [
            'execution_time' => 0,
            'memory_usage' => memory_get_peak_usage(true),
            'debug_info' => ['parse_failed' => true],
        ];

        self::logDebugInfo($requestData, $responseData, $executionInfo);
    }
}

